package webuser

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"goweb-goframe/internal/dao"
	"goweb-goframe/internal/model"
	"goweb-goframe/internal/packed"
	"strconv"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
)

// Register 用户账号注册
func (s sWebUser) Register(ctx context.Context, req *model.WebUserRegisterReq) (res string, err error) {
	var (
		salt     = genSalt()
		password = encryptPass(req.Password, salt)
	)
	db := dao.TbAccount.Ctx(ctx)
	// 用户不存在则可以注册，手机号为唯一键值，重复则不可以注册。
	id, _ := packed.GetID()
	_, err = db.Insert(g.Map{
		"id":                    strconv.FormatInt(int64(id), 10), // id 转字符存储
		"user_name":             req.UserName,
		"password":              password,
		"nike_name":             req.NikeName,
		"head_portrait":         nil,
		"phone_number":          req.PhoneNumber,
		"status":                1,
		"email":                 req.Email,
		"authentication_status": 0,
		"login_time":            gtime.Now(),
		"login_ip":              "172.168.1.1",
		"create_time":           gtime.Now(),
		"salt":                  salt,
		"base":                  0,
		"user_level":            0,
		"praise_num":            0,
	})
	// 报错则证明账号已注册
	if err != nil {
		err = gerror.New("账号已注册")
	}
	return
}
